package org.umss.fixturebuilder.builder;

import java.util.List;
import org.umss.fixturebuilder.builder.model.Phase;
import org.umss.fixturebuilder.builder.model.Game;
import org.umss.fixturebuilder.builder.model.Round;
import org.umss.fixturebuilder.builder.model.Team;
import org.umss.fixturebuilder.model.appengine.PhaseType;

/**
 *
 * @author Daniela Meneses
 */
public class AllAgainstAllPhaseBuilder implements PhaseBuilder {

    public AllAgainstAllPhaseBuilder() {
    }

    @Override
    public Phase generatePhase(List<Team> teams) {
        Phase fixture = new Phase(PhaseType.ALL_AGAINST_ALL);
        boolean evenTeamsCount = teams.size() % 2 == 0;
        int roundCount = evenTeamsCount ? teams.size() - 1 : teams.size();
        int gamesCount = evenTeamsCount ? teams.size() / 2 : (teams.size() / 2) + 1;
        int localIndexLimit = roundCount;
        int localIndex = 0;
        int visitorIndex = roundCount - 1;
        boolean switchLocal = false;
        Round round;
        for (int roundIndex = 0; roundIndex < roundCount; roundIndex++) {
            round = new Round();
            for (int gameIndex = 0; gameIndex < gamesCount; gameIndex++) {
                if (localIndex == localIndexLimit) {
                    localIndex = 0;
                }

                if (visitorIndex == -1) {
                    visitorIndex = roundCount - 1;
                }

                Game game;
                if (gameIndex == 0) {
                    if (evenTeamsCount) {
                        game = switchLocal
                                ? new Game(teams.get(localIndex), teams.get(roundCount))
                                : new Game(teams.get(roundCount), teams.get(localIndex));
                        switchLocal = !switchLocal;
                        round.addGame(game);
                    }
                } else {
                    game = new Game(teams.get(localIndex), teams.get(visitorIndex));
                    round.addGame(game);
                    visitorIndex--;
                }
                localIndex++;
            }
            fixture.addRound(round);
        }

        return fixture;
    }
}
